package com.solocredit.finance.ui.market.act

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.utils.DensityUtils
import com.solocredit.finance.base.utils.TitleBarUtil
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.ActMullaApplyBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.market.adapter.MullaApplyDaysAdapter
import com.solocredit.finance.ui.market.adapter.MullaApplyDetailsAdapter
import com.solocredit.finance.ui.market.impl.MullaApplyPresenterImpl
import com.solocredit.finance.ui.market.view.IMullaApplyView
import com.solocredit.finance.utils.decoration.GridSpacingItemDecoration
import com.solocredit.finance.utils.event.MullaBehaviorTracker
import com.solocredit.finance.utils.event.MullaEventData
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.MullaCustomDataHelper
import com.solocredit.finance.utils.helper.TestAnalysisAddEvent
import com.solocredit.finance.weight.seekbar.OnRangeChangedListener
import com.solocredit.finance.weight.seekbar.RangeSeekBar
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal
import androidx.core.graphics.toColorInt

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/1 19:21
 * @Annotation：申请贷款
 */
class MullaApplyAct: MvpAct<IMullaApplyView, MullaApplyPresenterImpl>(),IMullaApplyView {
    lateinit var binding: ActMullaApplyBinding
    //选择时间
    private var daysAdapter: MullaApplyDaysAdapter? = null
    //贷款明细
    private var detailsAdapter: MullaApplyDetailsAdapter? = null
    //埋点备注
    var eventRemark = ""

    companion object {
        private const val INTENT_KEY_PRODUCT = "product"
        private const val INTENT_KEY_TOKEN = "token"
        fun start(context: Context, pName: String, pToken: String) {
            val intent = Intent(context, MullaApplyAct::class.java)
            intent.putExtra(INTENT_KEY_PRODUCT, pName)
            intent.putExtra(INTENT_KEY_TOKEN, pToken)
            context.startActivity(intent)
        }
    }

    override fun createPresenter(): MullaApplyPresenterImpl {
        return MullaApplyPresenterImpl(this)
    }
    override fun getMullaRootView(): View {
        binding = ActMullaApplyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTitleBarColor("#FF8027FF".toColorInt())
        setMullaTextTitleColor("#FFFFFF".toColorInt())
        setMullaTextTitle(getString(R.string.apply_title))
        setMullaBackBtnRes(R.mipmap.mulla_back_white)
        setMullaRightBtnRes(R.mipmap.mulla_kefu_icon)
        if (MullaConfigs.isTanz()){
            setMullaLanguageBtnRes(R.mipmap.mulla_language_choose_white_icon)
        }

        initMullaRefreshLayout()
        initMullaDaysRecyclerView()
        initMullaDetailsRecyclerView()
        showMullaSubmitPointsView()
    }

    override fun initMullaListener() {
        //客服
        rootViewBinding.ivFun.setOnClickListener {
            showMullaKefuDialog(eventRemark,loadProductName(),loadProductToken())
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,eventRemark)
        }
        rootViewBinding.ivLanguage.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,eventRemark)
            showMullaLanguageDialog(eventRemark, isCancel = true, isCancelTouch = true, onSelectCallback = {
            })
        }
        binding.seekBar.setOnRangeChangedListener(object : OnRangeChangedListener {
            override fun onRangeChanged(view: RangeSeekBar?, leftValue: Float, rightValue: Float, isFromUser: Boolean) {
            }
            override fun onStartTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {
            }
            override fun onStopTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {
                val leftSeekBar = view?.leftSeekBar
                leftSeekBar?.let {
                    binding.textAmount.text = it.indicatorTextDecimalFormat.format(it.progress)
                }
                initMullaData()
            }
        })
        //提交
        binding.submitLayout.setOnClickListener {
            if (getMullaApplyAmount() == "0" || getMullaApplyDays().isEmpty()){
                return@setOnClickListener
            }
            showMullaLoading(isTOuchOut = false, isCancel = true)
            presenter.onMullaCreateApplyOrderAction()
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_APPLY_SUBMIT,eventRemark)
            // TODO: 申贷 批量埋点上报
            MullaBehaviorTracker.getInstance(MyApp.app).reportImmediately(null)
        }
    }

    override fun initMullaData() {
        showMullaLoading(isTOuchOut = false, isCancel = true)
        presenter.loadMullaApplyDataAction()

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(licenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /* 初始化刷新 */
    private fun initMullaRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            presenter.loadMullaApplyDataAction()
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 选择days列表
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun initMullaDaysRecyclerView(){
        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val decoration = DensityUtils.dp2px(9f)
        binding.recyclerView.addItemDecoration(GridSpacingItemDecoration(3,decoration,false))
        val layoutManager = GridLayoutManager(getContext(),3)
        binding.recyclerView.layoutManager = layoutManager
        daysAdapter = MullaApplyDaysAdapter(binding.recyclerView)
        daysAdapter?.setOnItemChildClickListener { _, _, position ->
            val item = this.daysAdapter?.getItem(position)
            item?.let {
                if (!it.optBoolean("isEnabled",true) || it.optBoolean("isSelect",false)){
                    return@setOnItemChildClickListener
                }
                daysAdapter?.let { adapter ->
                    for (i in 0..<adapter.itemCount){
                        val model = adapter.getItem(i)
                        model.put("isSelect",false)
                        if (i == position){
                            model.put("isSelect",true)
                        }
                    }
                }
            }
            daysAdapter?.notifyDataSetChanged()

            //刷新数据
            initMullaData()
        }
        binding.recyclerView.adapter = daysAdapter
    }

    /**
     * 初始化明细列表
     */
    private fun initMullaDetailsRecyclerView() {
        binding.rvDetails.setHasFixedSize(true)
        binding.rvDetails.isNestedScrollingEnabled = false
        binding.rvDetails.isFocusableInTouchMode = false //不需要焦点
        binding.rvDetails.layoutManager = LinearLayoutManager(this)
        detailsAdapter = MullaApplyDetailsAdapter(binding.rvDetails)
        binding.rvDetails.adapter = detailsAdapter
        binding.rvDetails.itemAnimator = DefaultItemAnimator()
        detailsAdapter?.setOnItemChildClickListener{ _, childView, _ ->
            if (childView.id == R.id.itemLayout) {//切换item

            }
        }
    }

    /**
     * 设置提交申请可获得几分数
     */
    private fun showMullaSubmitPointsView(){
        //提交申请获得积分数量
        binding.textPoints.text = String.format(getString(R.string.step_phonebook_add_points),MullaCustomConfigsHelper.getMullaApplyPoints())
    }

    /**
     * 获取查看的产品名称
     */
    override fun loadProductName(): String {
        return intent.extras?.getString(INTENT_KEY_PRODUCT).toString()
    }

    /**
     * 获取查看的产品Token
     */
    override fun loadProductToken(): String {
        return intent.extras?.getString(INTENT_KEY_TOKEN).toString()
    }

    /**
     * 获取贷款金额
     */
    override fun getMullaApplyAmount(): String {
        return binding.textAmount.text.toString()
    }

    /**
     * 获取贷款期限
     */
    override fun getMullaApplyDays(): String {
        var days = ""
        daysAdapter?.let {
            if (it.itemCount > 0){
                for (i in 0..< it.itemCount){
                    val item = it.getItem(i)
                    if (item.optBoolean("isSelect",false)){
                        days = item.optString("day")
                        break
                    }
                }
            }
        }
        return days
    }

    /**
     * 不可选择贷款额度
     */
    override fun showMullaNotOptionalViews() {
        binding.chooseAmountLayout.visibility = View.GONE
        binding.amountLayout.visibility = View.VISIBLE
    }

    /**
     * 允许选择贷款额度
     */
    override fun showMullaOptionalViews(data: JSONObject) {
        binding.chooseAmountLayout.visibility = View.VISIBLE
        binding.amountLayout.visibility = View.GONE

        val amount = BigDecimal(data.optString("amount","0")).stripTrailingZeros().toPlainString()
        var minAmount = BigDecimal(data.optString("minAmount","0")).stripTrailingZeros().toPlainString()
        val maxAmount = BigDecimal(data.optString("maxAmount","0")).stripTrailingZeros().toPlainString()
        val granularity = data.optString("granularity","100")
        if (minAmount.toFloat() >= maxAmount.toFloat()){
            minAmount = "${maxAmount.toFloat() - granularity.toFloat()}"
        }
        binding.seekBar.setIndicatorTextDecimalFormat(granularity)//刻度
        //最大值必须要比最小值大
        binding.seekBar.setRange(minAmount.toFloat(),maxAmount.toFloat())
        binding.seekBar.setProgress(amount.toFloat())

        binding.textMinAmount.text = minAmount
        binding.textMaxAmount.text = maxAmount
    }

    /**
     * 设置贷款期限
     */
    override fun showMullaDurationList(data: JSONObject) {
        if (daysAdapter?.itemCount == 0){
            //默认天数
            val defaultDays = data.optString("days")
            val daysArray = data.optJSONArray("daysArray")
            val dayList = arrayListOf<JSONObject>()
            if (daysArray != null) {
                //如果daysArray中没有defaultDays，需要将defaultDays添加到daysArray列表中
                var isNeedAdd = true
                for (i in 0..<daysArray.length()){
                    if (daysArray.optString(i) == defaultDays){
                        isNeedAdd = false
                        break
                    }
                }
                if (isNeedAdd){
                    daysArray.put(0,defaultDays)
                }

                for (i in 0..<daysArray.length()){
                    val day = daysArray.optString(i)
                    val obj = JSONObject()
                    obj.put("day",day)
                    obj.put("isSelect",day == defaultDays)
                    obj.put("isEnabled",true)
                    dayList.add(obj)
                }
            } else {
                val obj = JSONObject()
                obj.put("day",defaultDays)
                obj.put("isSelect",true)
                obj.put("isEnabled",true)
                dayList.add(obj)
            }
            daysAdapter?.data = dayList
        }
    }

    /**
     * 设置贷款明细
     */
    override fun showMullaDetailsList(data: JSONObject) {
        //去掉末尾的0
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        binding.textAmount.text = amount
        //加载优惠券列表
        presenter.loadMullaCouponListAction()

        //明细
        val array = data.optJSONArray("detailItemList")
        val dataList = arrayListOf<JSONObject>()
        if (array != null){
            for (i in 0..<array.length()){
                val item = array.optJSONObject(i)
                if (item.has("title") && item.optString("title") == "YES"){
                    dataList.add(item)
                }
            }
            for (i in 0..<dataList.size){
                val obj = dataList[i]
                val childArray = JSONArray()
                var isAddChild = false
                for (n in 0..<array.length()){
                    val item = array.optJSONObject(n)
                    if (obj.optString("showName") == item.optString("showName")){
                        isAddChild = true
                        continue
                    }
                    if (item.has("title") && item.optString("title") == "YES"){
                        isAddChild = false
                        continue
                    }
                    if (isAddChild){
                        childArray.put(item)
                    }
                }
                obj.put("childList",childArray)
            }
        }
        detailsAdapter?.data = dataList
    }

    /**
     * 设置优惠券数量
     */
    override fun showMullaCouponCounts(count: Int) {
        if (count == 0){
            //不显示优惠券数量
            binding.couponCountLayout.visibility = View.GONE
            return
        }
        binding.couponCountLayout.visibility = View.VISIBLE
        //可用优惠券数量
        val showTipsKey = String.format(getString(R.string.apply_coupon_count_key),count.toString())
        val showTipsText = String.format(getString(R.string.apply_coupon_count_tips),showTipsKey)
        val spString = SpannableString(showTipsText)
        val startIndex = showTipsText.indexOf(showTipsKey)
        spString.setSpan(ForegroundColorSpan("#FFFFAC25".toColorInt()), startIndex, startIndex + showTipsKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textCouponCount.text = spString
    }

    /**
     * 贷款申请成功
     */
    override fun showMullaApplySuccess() {
        //贷款申请成功 - 需要打点
        TestAnalysisAddEvent.addApplyEvent()
        MyApp.app.publisher.publish(MullaEventData(MullaEventData.TYPE.MULLA_PRODUCT_REFRESH))
        // TODO: 重置签到提额相关数据
        MullaCustomDataHelper.saveMullaCustomSignRiseLastTimeStampAndDays(0,"")
        //进入SMS权限使用说明页面
        MullaApplyWaitAct.start(this,loadProductName(),loadProductToken())

        launch(Dispatchers.Main){
            delay(500)
            finish()
        }
    }

    /**
     * 申请失败 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    override fun showMullaApplyFailed() {
        hideMullaLoading()
        finish()
    }

    override fun hideMullaLoading() {
        super.hideMullaLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        eventRemark = "${loadProductName()} Apply Page"
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_APPLY_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_APPLY_END,eventRemark)
    }
}